<?php
namespace app\common\model;



use app\user\model\UserRichesLog;
use app\common\service\PayService;

class Order extends TimeModel
{
    protected $json=['order_info'];
    protected $jsonAssoc = true;
    public function setUserIpAttr($value){
        return ip2long($value);
    }

    public function getUserIpAttr($value){
        return long2ip($value);
    }
    public function getPayStatusAttr($value){
        $arr=[
            0=>'未支付',
            1=>'已支付',
            -1=>'已退款',
        ];
        return $arr[$value];
    }
    static function checkAuth(){
        //检测是不是过期了
        //检测
        return true;
    }

    public static function submit($params){

        $subject = $params['subject'];
        $paytype = $params['pay_type'];
        $subject_id = isset($params['subject_id'])?$params['subject_id']:0;

        $orderTitle='积分充值';
        $user_coupon=null;
        $amount = 0;
        $uid=session('userid');
        $useCoupon=$useBalance=0;
        if($subject=='RECHARGE'){
            $min_recharge=sysconfig('score.min_recharge');
            $max_recharge=sysconfig('score.max_recharge');
            $subject_num=$params['subject_num'];
            if($min_recharge&&$max_recharge&&($subject_num<$min_recharge||$subject_num>$max_recharge)){
                return fail('充值金额不在系统规定的范围'.$min_recharge.'～'.$max_recharge,[],0);
            }
            $fee =$amount=$subject_num*sysconfig('score.score_price');
        }elseif($subject=='BUY_AD'){
            $res=hooks('adplan.adbuy_check', $params['order_info'],true);
            if($res['code']==0){
                return json($res);
            }
            $info=$res['data'];

            $fee =$amount= $info['fee'];
            $subject_id= $info['subject_id'];
            $orderTitle='购买广告位'.$subject_id;
            $data['order_info'] =  $params['order_info'];
        }elseif($subject=='ARTICLE'){
            $article=(new Article())->find($subject_id);
            if(!$article||$article->fee==0){
                return fail('文章不需要购买',[],0);
            }
            $orderTitle='购买'.$article->title;
            $fee=$amount=$article['fee'];
            if(!empty($params['user_coupon_id'])){
                $user_coupon=(new \app\model\UserCoupon())->where('user_id',$uid)
                    ->where('id',$params['user_coupon_id'])->find();
                if($user_coupon&&$user_coupon['money']<=$amount){
                    $data['coupon_cost'] =$user_coupon['money'];
                    $amount-=$user_coupon['money'];
                    $useCoupon=$user_coupon->id;
                }else{
                    return fail('优惠券金额必须小于等于文章金额',[],0);
                }
            }
            if($paytype=='balance'&&$amount>0){
                $user=cacheUser(1);
                $balance=$user['balance'];
                if($balance&&$amount<=$balance){
                    $data['balance_cost'] =$amount;
                    $useBalance=$amount;
                    $amount=0;
                }else{
                    return fail('余额不足',[],0);
                }
            }
        }
        $redirectUri=$params['redirect_uri'];
        $orderId = 'P' . date('YmdHis') . uniqid();
        $faqi=0;
        if($paytype!='balance'&&$amount>0) {
            $status=$dealStatus=0;
            $faqi=1;
        }else{
            $status=$dealStatus=1;
            $res=success('支付成功',['buy_status'=>1,'return_url'=>$redirectUri],0);
        }

        $payconfig=PaymentAccount::getItem($paytype);
        if(!$payconfig){
            return fail('收款账号信息未配置，请联系管理员',[],0);
        }
        $payment_account_id=$payconfig['id'];
        $data['uuid'] = uniqid();
        $data['subject'] = $subject;
        $data['subject_id'] = $subject_id;
        $data['order_title'] = $orderTitle;
        $data['amount'] = $fee;
        $data['pay_amount'] = $amount;
        $data['user_id'] = $uid;
        $data['user_ip'] = request()->ip();
        $data['status'] = $status;
//        $data['promo_uid'] = !empty($params['promo_uid'])?$params['promo_uid']:0;
        $data['order_no'] = $orderId;
        $data['pay_type'] = $paytype;
        $data['payment_account_id'] = $payment_account_id;

        $order= (new static())->create($data);
        if($useCoupon){
            (new \app\model\UserCoupon())->where('id',$useCoupon)->save(['status'=>1]);
        }
        if($useBalance){
            (new User())->where('id',$uid)->dec('balance',$useBalance)->inc('balance_locked',$useBalance)->update();
        }
        if($dealStatus){
            //扣除余额的
            static::processing($order);
        }
        if($faqi==1){

            $res = (new PayService())->submit($paytype,$payconfig,$amount, $orderId, $orderTitle,$redirectUri);
        }
        return $res;
    }

    public static function note($params)
    {

        $uid = cacheUserid();

        $payAmount = $params['amount'];
        $paymentId=$params['account_id'];
        $outTradeNo=$params['order_no'];
        //创建一个
        $insertData['user_id'] = $uid;
        $insertData['price'] = $params['price'];
        $insertData['amount'] = $payAmount;
        $insertData['user_ip'] =  $params['user_ip'];
        $insertData['order_no'] = $outTradeNo;
        $insertData['subject'] = ($params['subject']=='积分充值')?'DEFAULT':$params['subject'];
        $insertData['subject_num'] = $params['subject_num'];
        $insertData['subject_id'] = $params['subject_id'];
        (new static())->save($insertData);


        $data['order_no'] = $outTradeNo;
        $data['subject'] = $params['subject'];
        $data['body'] =  isset($params['body'])?$params['body']:$params['subject'];
        $data['pay_type'] = $params['pay_type'];
        $data['payment_account_id'] = $paymentId;
        $data['money'] = $payAmount;
        $data['user_ip'] = request()->ip();
        (new Pay())->save($data);
        (new PaymentAccount())->where('id',$paymentId)->inc('use_count')->update();
    }

    static function processing($orderId,$payStatus=1,$hand=0){
        $order=static::where('order_no',$orderId)->find();
            if($order&&$order['deal_status']==0){
                $order->pay_status=$payStatus;
                $order->is_hand=$hand;
                $order->deal_status=1;
                $order->save();
                $subject=$order['subject'];
                if($subject=='BUY_AD'){
                    //替换广告位
                    $res=hooks('adplan.adbuy_deal', $order['order_info'],true);
                }else {

                    if ($order['subject_id'] == 0) {
                        UserRichesLog::note($order['subject_num'], $order['user_id'], '积分充值', 1, $order['id'], 'ORDER');
                    } elseif ($order['subject_id'] > 0) {

                    }
                }
            }
    }
}